var app =require('express')()
var server =require('http').Server(app)
var io =require('socket.io')(server)
let users=[]

server.listen(3000,'192.168.1.119',()=>{
	console.log('运行了程序')
})
app.use(require('express').static('public'))
app.get('/',function(req,res){
	res.readirect('/index.html')
})
io.on('connection',function(socket){
	console.log('用户连接了')
	socket.on('login',data=>{
		let user =users.find(item=>item.username===data.username)
		if(user){
			socket.emit('loginErr',{msg:'登陆失败'})
			console.log('登录失败')
		}else{
			socket.money =998
			users.push(data)
			let suc ={username:data.username,avatar:data.avatar,money:socket.money}
			socket.emit('loginSuccess',suc)
			io.emit('addUser',suc)
			console.log('登录成功',suc)
			io.emit('userList',users)
			socket.username=data.username
			socket.avatar=data.avatar
			
		}
	})
    socket.on('disconnect',()=>{
		//删除users
		let idx =users.findIndex(item=>item.username===socket.username)
		users.splice(idx,1)
		//广播退出消息
		io.emit('delUser',{username:socket.username,avatar:socket.avatar})
		//更新列表
		io.emit('userList',users)
    })
    socket.on('sendMessage',data=>{  	
    	io.emit('receiveMessage',data)
    })

    socket.on('sendImage',data=>{  	
    	io.emit('receiveImage',data)
    })
    socket.on('sendmoney',data=>{
    	socket.money-=data.dd
    	socket.emit('upmoney',socket.money)
    	let str ={money:socket.money,arr:data.arr,username:socket.username,avatar:socket.avatar}
    	io.emit('changemoney',str)
    })
})
